package com.bbjob.toolutil;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;

public class HttpClientUtil {

	public static String doGet(String url, Map<String, String> param) {
		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();
		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();

			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);

			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(),
						"UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	public static String doGet(String url) {
		return doGet(url, null);
	}

	public static String doPost(String url, Map<String, Object> params) {
		String charset = "utf-8";
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String resultString = "";
		// 创建Http Post请求
		HttpPost httpPost = new HttpPost(url);

		httpPost.addHeader("Content-type", "application/json; charset=utf-8");
		httpPost.setHeader("Accept", "application/json");
		List<NameValuePair> pairs = null;
		if (params != null && !params.isEmpty()) {
			pairs = new ArrayList<NameValuePair>(params.size());
			for (Map.Entry<String, Object> entry : params.entrySet()) {
				Object value = entry.getValue();
				if (value != null) {
					pairs.add(new BasicNameValuePair(entry.getKey(), value
							.toString()));
				}
			}
		}

		if (pairs != null && pairs.size() > 0) {
			String bodyStr = new Gson().toJson(params);
			httpPost.setEntity(new StringEntity(bodyStr, charset));
		} else {

			httpPost.setEntity(new StringEntity("{}", charset));
		}
		CloseableHttpResponse response = null;

		try {
			response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				httpPost.abort();
				throw new RuntimeException("httpClient, error status code: "
						+ statusCode);
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {

				result = EntityUtils.toString(entity, "utf-8");
			}
			EntityUtils.consume(entity);

			return result;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static String doPost(String url) {
		return doPost(url, null);
	}

	/**
	 * 请求的参数类型为json
	 * 
	 * @param url
	 * @param json
	 * @return {username:"",pass:""}
	 */
	public static String doPostJson(String url, String json) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建请求内容
			StringEntity entity = new StringEntity(json,
					ContentType.APPLICATION_JSON);
			httpPost.setEntity(entity);
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	public static String doPost(String url, File file,
			Map<String, Object> params) {

		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String result = null;

		try {
			MultipartEntity reqEntity = new MultipartEntity();
			FileBody bin = new FileBody(file);
			reqEntity.addPart("file", bin);

			if(params.get("uniquecode") != null) {
				reqEntity.addPart("uniquecode", new StringBody(params.get("uniquecode").toString(), Charset.forName("UTF-8")));
			}
			if(params.get("filename") != null) {
				reqEntity.addPart("filename", new StringBody(params.get("filename").toString(), Charset.forName("UTF-8")));
			}
			if(params.get("eId") != null) {
				reqEntity.addPart("eId", new StringBody(params.get("eId").toString(), Charset.forName("UTF-8")));
			}
			
			if(params.get("eName") != null) {
				reqEntity.addPart("eName", new StringBody(params.get("eName").toString(), Charset.forName("UTF-8")));
			}
			if(params.get("eClassify") != null) {
				reqEntity.addPart("eClassify", new StringBody(params.get("eClassify").toString(), Charset.forName("UTF-8")));
			}
			if(params.get("eStarttimeStr") != null) {
				reqEntity.addPart("eStarttimeStr", new StringBody(params.get("eStarttimeStr").toString(), Charset.forName("UTF-8")));
			}
			if(params.get("eEndtimeStr") != null) {
				reqEntity.addPart("eEndtimeStr", new StringBody(params.get("eEndtimeStr").toString(), Charset.forName("UTF-8")));
			}
			if(params.get("eTimeLength") != null) {
				reqEntity.addPart("eTimeLength", new StringBody(params.get("eTimeLength").toString(), Charset.forName("UTF-8")));
			}
			if(params.get("passingGrade") != null) {
				reqEntity.addPart("passingGrade", new StringBody(params.get("passingGrade").toString(), Charset.forName("UTF-8")));
			}
			if(params.get("answerNumber") != null) {
				reqEntity.addPart("answerNumber", new StringBody(params.get("answerNumber").toString(), Charset.forName("UTF-8")));
			}
			if(params.get("eMode") != null) {
				reqEntity.addPart("eMode", new StringBody(params.get("eMode").toString(), Charset.forName("UTF-8")));
			}
			if(params.get("status") != null) {
				reqEntity.addPart("status", new StringBody(params.get("status").toString(), Charset.forName("UTF-8")));
			}
			if(params.get("remark") != null) {
				reqEntity.addPart("remark", new StringBody(params.get("remark").toString(), Charset.forName("UTF-8")));
			}
			if(params.get("qId") != null) {
				reqEntity.addPart("qId", new StringBody(params.get("qId").toString(), Charset.forName("UTF-8")));
			}
			
			
			HttpPost httpPost = new HttpPost(url);

			httpPost.setEntity(reqEntity);
			response = httpClient.execute(httpPost);

			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				httpPost.abort();
				throw new RuntimeException("httpClient, error status code: "
						+ statusCode);
			}
			HttpEntity entity = response.getEntity();
			if (entity != null) {

				result = EntityUtils.toString(entity, "utf-8");
			}
			EntityUtils.consume(entity);

			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return null;
	}

	public static String doGetWithMinSeconds(String url) {
		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();
/*		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);*/
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(1000).setSocketTimeout(1000).build();
		
		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			URI uri = builder.build();

			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);
			httpGet.setConfig(requestConfig);
			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(),
						"UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}
}